//
//  HEMineRecordCell.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/10/16.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEMineRecordCell.h"
#import "HEHealthRecordCell.h"
#import "HEHealthRecodAddCell.h"
#import "HERealNameAuthAlterController.h"
#import "HEHealthRecordViewController.h"
#import "HEAddBindUserViewController.h"
#import "MineViewController.h"

@interface HEMineRecordCell()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (strong, nonatomic) UILabel *titleLb;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, assign) BOOL hasAuth;
@property (nonatomic, strong) QMUIButton *addBtn;
@property (nonatomic, strong) NSArray <HEBindUserModel *> *bindUsers;
@end

@implementation HEMineRecordCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.contentView.backgroundColor = KWhiteColor;
        
        [self initUI];
        
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshUserInfo) name:KNotificationUserInfoChange object:nil];
    }
    return self;
}

- (void)refreshUserInfo:(NSArray <HEBindUserModel *> *)users {
    _bindUsers = users;
//    _hasAuth = [UserManager sharedUserManager].curUserInfo.verifyStatus;
    _hasAuth = users.count >= 1;
    [self.collectionView reloadData];
    [self initAddBtn];
}

- (void)initAddBtn {
    if (_hasAuth && !_addBtn) {
        QMUIButton *addBtn = [[QMUIButton alloc] init];
        _addBtn = addBtn;
        addBtn.imagePosition = QMUIButtonImagePositionLeft;
        addBtn.adjustsImageTintColorAutomatically = NO;
        addBtn.spacingBetweenImageAndTitle = 5;
        [addBtn setImage:IMAGE_NAMED(@"add_blue") forState:UIControlStateNormal];
        [addBtn setTitle: @"添加老人" forState:UIControlStateNormal];
        [addBtn setTitleColor:CNavBgColor forState:UIControlStateNormal];
        addBtn.titleLabel.font = DYBlodFont(16);
        [self.contentView addSubview:addBtn];
        [addBtn setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
        
        [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_titleLb.mas_centerY);
            make.right.equalTo(self.contentView).mas_offset(-15);
        }];
        
        [addBtn addTarget:self action:@selector(addBindUserClick) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)initUI {
    
    // 标题
    _titleLb = [UILabel new];
    _titleLb.text = @"健康档案";
    [self.contentView addSubview:_titleLb];
    _titleLb.font = DYFont(21);
    
    [_titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).mas_offset(15);
        make.left.equalTo(self.contentView).mas_offset(15);
        make.right.equalTo(self.contentView).mas_offset(-15);
     }];
    
    // 1.创建流水布局
    _layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//    _layout.estimatedItemSize = CGSizeMake(120, 100);

    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
    _collectionView.backgroundColor = KWhiteColor;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    if (@available(iOS 11.0, *)) {
        _collectionView.contentInsetAdjustmentBehavior = NO;
    } else {
        // Fallback on earlier versions
    }
    [self.contentView addSubview:_collectionView];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_titleLb.mas_bottom).mas_offset(10);
        make.left.right.equalTo(self.contentView);
        make.bottom.equalTo(self.contentView).mas_offset(-7);
    }];
    
    /// 设置此属性为yes 不满一屏幕 也能滚动
    self.collectionView.alwaysBounceHorizontal = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    [_collectionView registerClass:HEHealthRecordCell.class forCellWithReuseIdentifier: KHEHealthRecordCell]; 
    [_collectionView registerClass:HEHealthRecodAddCell.class forCellWithReuseIdentifier: KHEHealthRecodAddCell];

    
//    _manContent = [[UIScrollView alloc] init];
//    _manContent.scrollEnabled = YES;
//    _manContent.showsVerticalScrollIndicator = NO;
//    _manContent.showsHorizontalScrollIndicator = NO;
//    [self.contentView addSubview:_manContent];
//
//    [_manContent mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(_titleLb.mas_bottom).mas_offset(10);
//         make.left.equalTo(self.contentView).mas_offset(10);
//         make.right.equalTo(self.contentView).mas_offset(-10);
//         make.bottom.equalTo(self.contentView).mas_offset(-5);
//     }];
    
//    NSMutableArray *manArr = [NSMutableArray array];
//
//    for (int i = 0; i < 1; i++) {
//        UIView *cardView = [UIView new];
//        cardView.backgroundColor = [UIColor colorWithRed:62/255.0 green:139/255.0 blue:248/255.0 alpha:1.0];
//        cardView.layer.shadowColor = [UIColor colorWithRed:58/255.0 green:58/255.0 blue:58/255.0 alpha:0.08].CGColor;
//        cardView.layer.shadowOffset = CGSizeMake(0,2);
//        cardView.layer.shadowOpacity = 1;
//        cardView.layer.shadowRadius = 4;
//        cardView.layer.cornerRadius = 6;
//        [_manContent addSubview:cardView];
//
//        // 姓名
//        UILabel *nameLb = [UILabel new];
//        [cardView addSubview:nameLb];
//        nameLb.text = @"张三";
//        nameLb.font = DYBlodFont(18);
//        nameLb.textColor = KWhiteColor;
//
//        [nameLb mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(cardView).mas_offset(10);
//            make.left.equalTo(cardView).mas_offset(10);
//            make.right.equalTo(cardView).mas_offset(-10);
//        }];
//
//        // 描述
//        UILabel *descLb = [UILabel new];
//        [cardView addSubview:descLb];
//        descLb.text = [NSString stringWithFormat:@"本人    %d岁", 18];
//        descLb.font = DYFont(15);
//        descLb.textColor = KWhiteColor;
//
//        [descLb mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(nameLb.mas_bottom).mas_offset(13);
//            make.left.equalTo(cardView).mas_offset(10);
//            make.right.equalTo(cardView).mas_offset(-10);
//            make.bottom.equalTo(cardView).mas_offset(-10);
//        }];
//
//        [manArr addObject:cardView];
//    }
//
//    [manArr mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.greaterThanOrEqualTo(@115);
//        make.height.greaterThanOrEqualTo(@70);
//    }];
//
//    // 实现masonry水平固定间隔方法
//    [manArr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:10 leadSpacing:0 tailSpacing:0];
//
//    [_manContent setupAutoContentSizeWithRightView:manArr.lastObject rightMargin:0];
 }

//解决ios8上自动布局的问题
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}


#pragma mark - 代理方法 Delegate Methods
// 设置分区

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

// 每个分区上得元素个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _bindUsers.count == 0 ? 1 : _bindUsers.count;
}

// 设置cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_hasAuth) {
        HEHealthRecordCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: KHEHealthRecordCell forIndexPath:indexPath];
        [cell refreData: _bindUsers[indexPath.item]];
        return cell;

    }else {
        HEHealthRecodAddCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: KHEHealthRecodAddCell forIndexPath:indexPath];
        return cell;
    }
}

// 设置cell大小 itemSize：可以给每一个cell指定不同的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
 //    CGFloat width = [self gainStringWidthWithString:self.nameArray[indexPath.row] font:15.0f height:height];
    return CGSizeMake(115, 70);
}


// 设置UIcollectionView整体的内边距（这样item不贴边显示）
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    // 上 左 下 右
    return UIEdgeInsetsMake(0, 15 , 0, 15);
}

// 设置minimumLineSpacing：cell上下之间最小的距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 15;
}

// 设置minimumInteritemSpacing：cell左右之间最小的距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 15;
}

// 选中cell的回调
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (!_hasAuth) {
        [self toVaildRealUser];
        return;
    }
    
    HEHealthRecordViewController *vc = [HEHealthRecordViewController new];
    vc.userModel = _bindUsers[indexPath.item];
    [_vc.navigationController pushViewController:vc animated:YES];
}

- (void)toVaildRealUser {
    if (![[UserManager sharedUserManager] getUserInfo].verifyStatus) {
        HERealNameAuthAlterController *vc = [HERealNameAuthAlterController new];
        [_vc.view addSubview:vc.view];
     }
}

- (void)addBindUserClick {
    HEAddBindUserViewController *vc = [HEAddBindUserViewController new];
    [_vc.navigationController pushViewController:vc animated:YES];
    MineViewController *superVC = (MineViewController *)_vc;
    KWeakSelf
    vc.backBlock = ^{
        [superVC getBindUserData];
    };
}

@end
